﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using lumo.display.object2D;
using Microsoft.Xna.Framework;

namespace lumo.display.animation2D
{
    /// <summary>
    /// An angle animation for an object.
    /// </summary>
    public class FrameAnimation2D : GenericAnimation2D<ICroppable>
    {
        // Private variables
        private uint   XDivisions;
        private uint   YDivisions;
        private uint   FrameMax;
        private uint[] Pattern;
        private Counter AnimIndexCounter = new Counter();

        /// <summary>
        /// Constructor
        /// </summary>
        public FrameAnimation2D(uint XDivisions, uint YDivisions, uint[] Pattern, float Time, Smooth Smoothness = Smooth.None, Loop LoopMode = Loop.None, ICroppable CurrentObject = null)
            : base(Time, Smoothness, LoopMode, CurrentObject)
        {
            this.XDivisions = XDivisions;
            this.YDivisions = YDivisions;
            this.FrameMax = (this.XDivisions * this.YDivisions);
            this.Pattern = Pattern;
            if (this.FrameMax <= 0)
                throw new Exception("Invalid Parameters for FrameAnimation2D");
        }

        /// <summary>
        /// Check if finished
        /// </summary>
        public override bool Finished { get { return (AnimIndexCounter.Finished); } }

        /// <summary>
        /// Setup the values
        /// </summary>
        internal override void SetupValues()
        {
            AnimIndexCounter.Reset(0, this.Pattern.Length, this.Time, this.Smoothness, this.LoopMode);
        }

        /// <summary>
        /// Update the values.
        /// </summary>
        /// <param name="Game">The game class</param>
        internal override void UpdateValues(LumoComponent Game)
        {
            AnimIndexCounter.Update(Game);
            int Index = (int)(Math.Min(Math.Floor(AnimIndexCounter.Value), this.Pattern.Length - 1));
            SetFrame(this.Pattern[Index]);
        }

        /// <summary>
        /// Update the values.
        /// </summary>
        /// <param name="Id">The Id of animation object</param>
        private void SetFrame(uint Id)
        {
            Vector2 Size = this.CurrentObject.OriginalSize;
            int FrameWidth  = (int)(Size.X / XDivisions);
            int FrameHeight = (int)(Size.Y / YDivisions);
            this.CurrentObject.SourceRectangle = new Rectangle((int)(FrameWidth * (Id % FrameMax)), (int)(FrameHeight * (Id / FrameMax)), FrameWidth, FrameHeight);
        }
    }
}
